<?php
class modelModel extends hopeCmsModel
{

	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
    {
        return '{model}';
    }

    public function primaryKey()
    {
        return 'model_id';
    }

    /**
     * 获取所有模型名
     */
    public function getModelName()
    {
        $models = $this->findsByAttribute('model_id, name', 'disabled=1');

        foreach ($models as $m) {
            $model[$m['model_id']] = $m['name'];
        }

        return $model;
    }

    /**
     * 获取模型html option
     */
    public function getModelHtmlOption($mid = 0, $name='model_id')
    {
        $select  = '<select class="html_select" name="'.$name.'" v="re" msg="请选择所属模型">';
        $select .= '<option value="">≡ 请选择模型 ≡</option>';
        $models  = $this->findsByAttribute('model_id, name', 'disabled=1');
        foreach ($models as $model) {
            if ($mid == $model['model_id']) {
                $se = ' selected="selected" ';
            } else {
                $se = '';
            }
            $select .= '<option value="'.$model['model_id'].'"'.$se.'>'.$model['name'].'</option>';
        }
        $select .= '</select>';
        return $select;
    }

    /**
     * 保存前置操作
     */
    public function beforeSave()
    {
        $_POST['name']        = trim(htmlspecialchars($_POST['name']));
        $_POST['table_name']  = trim(htmlspecialchars($_POST['table_name']));
        $_POST['description'] = trim(htmlspecialchars($_POST['description']));
    
        $_POST['source']      = explode("\n", $_POST['source']);
        $_POST['source']      = implode('|', array_filter($_POST['source']));
        $this->setData($_POST);
        return true;
    }

    /**
     * 获取模型信息
     */
    public function getModelInfo($mid)
    {
        $info = $this->findByPk($mid);
        $info['source'] = str_replace('|', PHP_EOL, $info['source']);
        return $info;
    }

    public function scopes()
    {
        return array(
            'recently' => array(
                'order' => '{0}',
                'limit' => '{1}'
            ),
        );
    }
}
?>